from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser, UnicodeUsernameValidator, PermissionsMixin, Group,
    Permission
)
from django.utils import timezone
from server import settings
from django.contrib.auth.models import User


class MyUserManager(BaseUserManager):
    def get_queryset(self):
        return super().get_queryset().filter(is_deleted=False)

    def create(self, **kwargs):
        pass

    def create_user(self, **kwargs):
        if not kwargs['username']:
            raise ValueError('用户名不能为空')

        if not kwargs['password']:
            raise ValueError('密码不能为空')

        user = User(**kwargs)
        user.set_password(kwargs['password'])
        user.save(using=self._db)
        # 添加默认权限
        # user.user_permissions.add(Permission.objects.filter(codename='user_changeSelf')[0])
        # user.user_permissions.add(Permission.objects.filter(codename='user_deleteSelf')[0])
        return user

    def create_superuser(self, username=None, password=None):
        if not username:
            raise ValueError('用户名不能为空')

        if not password:
            raise ValueError('密码不能为空')

        user = User(username=username)
        user.set_password(password)
        user.is_active = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


class User(AbstractBaseUser, PermissionsMixin):
    """
    所有字段：
        username, nickname, real_name, avatar, gender, email, date_joined, last_login
        password, is_active, is_deleted, is_staff, groups, as_user_id, date_of_birth
        is_superuser, user_permissions
    """

    class Meta:
        verbose_name = "用户"  # 表名改成中文名
        verbose_name_plural = verbose_name

    username_validator = UnicodeUsernameValidator()  # django提供的用户名验证器
    username = models.CharField(
        verbose_name='用户名',
        max_length=150,
        unique=True,
        blank=False,
        null=False,
        validators=[username_validator],
        error_messages={
            'unique': "用户名已存在",
        },
    )
    nickname = models.CharField(
        verbose_name='昵称',
        max_length=64,
        blank=True,
        null=True)
    real_name = models.CharField(
        verbose_name='姓名',
        max_length=64,
        blank=True,
        null=True)
    avatar = models.ImageField(
        default=settings.DEFAULT_AVATAR,
        verbose_name='头像',
        upload_to='avatar/',  # 设置上传文件路径，基于MEDIA_ROOT目录下的子目录
    )
    GENDER_CHOICES = [
        (0, '未知'),
        (1, '女'),
        (2, '男')
    ]
    gender = models.IntegerField(
        verbose_name='性别',
        choices=GENDER_CHOICES,
        default='0',
        blank=True,
        null=True
    )
    email = models.EmailField(
        verbose_name='邮箱',
        max_length=255,
        blank=True,
        unique=True,
        null=True
    )
    date_of_birth = models.DateField(
        verbose_name='出生日期',
        blank=True,
        null=True)
    is_active = models.BooleanField(
        verbose_name='激活',
        default=True if settings.REGISTER_EMAIL_CAPTCHA_ON is False else False,
        help_text='账户是否激活'
    )
    is_deleted = models.BooleanField(
        verbose_name='删除',
        default=False,
        help_text='账户是否已经被删除'
    )
    is_staff = models.BooleanField(
        verbose_name='允许登录管理页面',
        default=False,
        help_text='是否允许用户登录管理页面',
    )
    date_joined = models.DateTimeField(
        verbose_name='注册日期',
        auto_now_add=True,
    )
    groups = models.ManyToManyField(
        Group,
        verbose_name='groups',
        blank=True,
        help_text='''
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ''',
        related_name="user_set",
        related_query_name="user",
        through='UserGroup'
    )

    as_user_id = models.CharField(
        verbose_name='认证后端用户id',
        max_length=128,
        unique=True,
        blank=False,
        null=True,
    )

    objects = MyUserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    def delete(self, using=None, keep_parents=False):
        self.is_deleted = True
        self.save()

    def __str__(self):
        return self.username


class UserGroup(models.Model):
    class Meta:
        db_table = 'user_user_group'
        verbose_name = '用户组'
        verbose_name_plural = "用户组"

    user = models.ForeignKey(
        User,
        verbose_name='用户',
        on_delete=models.CASCADE
    )
    group = models.ForeignKey(
        Group,
        verbose_name='组',
        on_delete=models.CASCADE
    )
    is_admin = models.BooleanField(
        verbose_name='是否为该组的管理员',
        default=False
    )


class InactiveManager(models.Manager):
    def create(self, activate_key, user):
        record = Inactive.objects.all().filter(user=user).first()
        if record:
            record.activate_key = activate_key
            record.save()
        else:
            record = Inactive()
            record.activate_key = activate_key
            record.user_id = user.id
            record.save()
        self.clear_cache()

    def clear_cache(self):
        records = Inactive.objects.all()
        for record in records:
            user = User.objects.filter(id=record.user_id)
            if not user:
                record.delete()


class Inactive(models.Model):
    activate_key = models.CharField(
        max_length=256,
        unique=True,
        null=False
    )
    user = models.ForeignKey(
        to=User,
        on_delete=models.CASCADE
    )
    objects = InactiveManager()
